/*********************************************/

// 次文件只需要关注 getBars 和 subscribeBars 函数即可

/******************************************/

// 历史数据 第一条数据的 时间撮 因为k线图一次性历史数据只拿一部分，用户吧图往前滑动，就会用这个时间撮去请求更早的 历史数据
var detafeed_historyTime = 0
// 上一次的 K线周期 切换产品的时候 需要从websock 取消订阅这个
var detafeed_lastResolution = null
// 上一次的产品 切换产品的时候 需要从websock 取消订阅这个
var detafeed_lastSymbol = null

var cacheData = {}

function FeedBase() {
	// console.log("init FeedBase")
}

FeedBase.prototype.onReady = function(callback) {
	setTimeout(function() {
		callback(this._configuration)
	}, 0)
}

FeedBase.prototype.getSendSymbolName = function(symbolName) {
	var name = symbolName.split('/')
	return (name[0] + name[1]).toLocaleLowerCase()
}

FeedBase.prototype.resolveSymbol = function(symbolName, onResolve, onError) {
	setTimeout(function() {
		onResolve({
			name: symbolName,
			timezone: "Asia/Shanghai", // UTC/GMT
			pricescale: 100,
			minmov: 1,
			minmov2: 0,
			ticker: symbolName,
			description: "",
			type: 'futures',
			format: 'price',
			volume_precision: 10,
			has_intraday: true,
			intraday_multipliers: ['1', '5', '15', '30', '60', '240', '1440'], // 时间
			volume_precision: 10,
			has_weekly_and_monthly: false,
			has_no_volume: false,
			session: "0930-1500",
			regular_session: "0930-1500"
		})
	}, 0)
}


/**
 * 更多时间类型在这里添加 时间类型请看火币文档
 * @param resolution  订阅周期 按照自己喜欢的来 如 30 30分钟、 1D 一天 
 * @param name 交易对symbol
 * @param to 结束时间
 * @returns {object}
 */
const resolutionFormat = (resolution, name, to) => {
	let req = `sub.futures.kline`;
	let minutes = 'm'+ resolution;
	
	if (resolution.includes('D')) {
		if (resolution.length < 2) resolution = '1' + resolution;
		req = `sub.futures.kline`;
		minutes = `${resolution}`;
		// minutes = parseInt(resolution) * 24 * 60;
	} else if (resolution.includes('W')) {
		if (resolution.length < 2) resolution = '1' + resolution;
		req = `sub.futures.kline`;
		minutes = `week`;
		// minutes = parseInt(resolution) * 24 * 60 * 7;
	} else if (resolution.includes('M')) {
		if (resolution.length < 2) resolution = '1' + resolution;
		req = `sub.futures.kline`;
		minutes = `month`;
		// minutes = parseInt(resolution) * 24 * 60 * 30;
	} else {
		if (resolution / 60 > 1) {
			req = `sub.futures.kline`;
			minutes = `${resolution / 60}h`;
		}
	}
	let code = name;
	let from = null;
	if (to) {
		from = to - 200 * minutes * 60;
		if (resolution.includes('M') || resolution.includes('W')) { // 周线月线控制条数，时间超出火币规定范围, ws报错
			from = to - 50 * minutes * 60;
		}
	}
	return {
		minutes,
		req,
		from,
		to,
		code,
	};
};

FeedBase.prototype.getBars = function(symbolInfo, resolution, rangeStartDate, rangeEndDate, onResult, onError) {

	var ticker = symbolInfo.name + "-" + resolution;
	var tickerload = ticker + "load";
	var tickerstate = ticker + "state";
	
	if(cacheData[tickerstate]) {
		// return false
	}
	
	cacheData[tickerload] = rangeStartDate

	// 切换产品周期 或者 切换产品 会执行这个函数
	let reso = resolutionFormat(resolution, symbolInfo.name, rangeEndDate > detafeed_historyTime ? rangeEndDate : detafeed_historyTime)
	// 是历史数据 
	var history = true
	/*
	  !detafeed_historyTime 如果没请请求过这个产品或者这个周期的历史数据
	  resolution !== detafeed_lastResolution 是否更换了产品周期
	  detafeed_lastSymbol !== symbolInfo.name 是否切换了产品
	*/
	if (!detafeed_historyTime || (resolution !== detafeed_lastResolution) || detafeed_lastSymbol !== symbolInfo.name) {
		// 那就不是历史数据
		history = false
		// 储存请求过的产品
		detafeed_lastSymbol = symbolInfo.name
		// 记录目前时间戳，就用目前时间戳往前请求历史数据
		detafeed_historyTime = window.parseInt((Date.now() / 1000))
	}
	
	console.log(history)
	
	/*
	  @socket.sendData
	  第一个参数订阅历史数据
	  第二个参数订阅实时数据
	  第三个参数 是  是否是历史数据
	*/
	socket.sendData({
		req: reso.req,
		minutes: reso. minutes,
		code: reso.code,
		from: reso.from,
		to: reso.to,
	}, reso.req, history)

	Event.off('data')
	Event.on('data', data => {
		if (data && Array.isArray(data)) {
			// 记录这次请求的时间周期
			detafeed_lastResolution = resolution
			var meta = {
				noData: false
			}
			const datas = []
			if (data.length) {
				detafeed_historyTime = data[0].time * 1000
				for (let i of data) {
					i.time = i.time * 1000
					i.close = Number(i.close)
					i.volume = Number(i.volume)
					datas.push(i)
				}
			} else {
				meta = {
					noData: true
				}
			}
			
			// 设置状态为true
			cacheData[tickerstate] = !0
			
			onResult(datas, meta)
		}
	})
}

// 				subscribeBars
// symbolInfo:			object 			SymbolInfo
// resolution: 			string 			周期
// onTick: function(bar)  bar:object{time, close, open, high, low, volume}
// listenerGuid: 		object
// onResetCacheNeededCallback(从1.7开始): function()将在bars数据发生变化时执行
FeedBase.prototype.subscribeBars = function(symbolInfo, resolution, onTick, listenerGuid, onResetCacheNeededCallback) {
	Event.off('realTime')
	// 拿到实时数据 在这里画
	Event.on('realTime', data => {
		if (Object.prototype.toString.call(data) === '[object Object]' && data.hasOwnProperty('open')) {
			// 当您调用onTick且K线时间等于最新K线时间时，那么这条最新K线将被您传入的K线所替换
			// 例:
			// 最近一条K线为 {1419411578413, 10, 12, 9, 11}
			// 调用 onTick({1419411578413, 10, 14, 9, 14})
			// 图表库通过时间1419411578413找出K线，已存在并且是最近的那一个
			// 图表库替换K线，因此现在最近一条K线为 {1419411578413, 10, 14, 9, 14}
			// 现在，在图表接收到数据后，没有办法改变历史上的K线
			/*onTick({
				time: data.time * 1000,
				close: Number(data.close),
				// open: Number(data.open),
				// high: Number(data.high),
				// low: Number(data.low),
				volume: Number(data.volume)
			})*/
		}
	})
}


// listenerGuid:object
// 取消订阅K线数据。在调用subscribeBars方法时,图表库将跳过与listenerGuid相同的对象。
FeedBase.prototype.unsubscribeBars = function(listenerGuid) {
	// 取消订阅产品的callback
}
